package com.ken.teacher.server;



import com.alibaba.fastjson2.JSON;
import com.ken.teacher.pojo.MessagePayload;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

@ServerEndpoint("/attendance/websocket")
@Component
@Slf4j
public class WebSocketServer {
    private static RedisTemplate<String,String> redisTemplate;
    private static Map<String, Session> sessionMap = new ConcurrentHashMap<>(); // 会话映射
    @Autowired
    public void setRedisTemplate(RedisTemplate<String,String> redisTemplate){
        WebSocketServer.redisTemplate=redisTemplate;
    }
    @OnOpen
    public void onOpen(Session session) {
        // 假设您有某种方式来识别前端，这里简单以sessionId为例
        String identifier = session.getId();
        sessionMap.put(identifier, session);
        System.out.println("WebSocket连接开启：" + identifier);
    }

    @OnMessage
    public void onMessage(String message, Session session) throws Exception {
        log.info("发起考勤");
        // 使用Fastjson2解析JSON字符串
        MessagePayload payload = JSON.parseObject(message, MessagePayload.class);
        // 直接从payload对象中访问class_id和time
        String classId = payload.getClassId();
        long time = payload.getTime();
        redisTemplate.opsForValue().set(classId,session.getId(),time, TimeUnit.SECONDS);
        //todo 开启定时任务，统计未签到的学生信息存入数据库
    }

    @OnClose
    public void onClose(Session session) {
        String identifier = session.getId();
        sessionMap.remove(identifier);
        System.out.println("WebSocket连接关闭：" + identifier);

    }
    public static Session getSession(String sessionId){
        return sessionMap.get(sessionId);
    }
}
